home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Language/OS - Multiplatform Resource Library
/
LANGUAGE OS.iso
/
cpp_libs
/
answrbok
/
4_6.lha
/
4_6
/
4_6b.c
< prev
next >
Wrap
Text File
|
1993-08-08
|
2KB
|
106 lines
* Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
* The C++ Answer Book */
* Tony Hansen */
* All rights reserved. */
/ quick sort
/ Version 2
/ Based on "Algorithms" by Robert Sedgewick
/ Chapter 9, pp 103-113
include <swap.h>
/ Global variables
tatic int *a;
onst int cutoff = 16;
/ insertion sort to finish the job off
tatic void inssort(int left, int right)
for (int i = left + 1; i <= right; i++)
{
int v = a[i];
for (int j = i, k = j-1;
j > 0 && a[k] > v;
j--, k--)
a[j] = a[k];
a[j] = v;
}
/ partition the array into two halves
/ after the partition,
/ K[left] < ... < K[i] < ... < K[right]
/ iqsort will then recursively sort
/ K[left] through K[i-1] and
/ K[i+1] through K[right]
tatic int partition(int left, int right)
// sort-three: sort left, middle and right elements
// to find the partitioning element
int mid = (left + right) / 2;
if (a[left] > a[mid])
swap(a[left], a[mid]);
if (a[left] > a[right])
swap(a[left], a[right]);
if (a[mid] > a[right])
swap(a[mid], a[right]);
// move the partitioning element
// to the right end
int j = right - 1;
swap(a[mid], a[j]);
int i = left;
int v = a[j];
do {
do {
i++;
} while (a[i] < v);
do {
j--;
} while (a[j] > v);
swap(a[i], a[j]);
} while (i < j);
swap(a[j], a[i]);
swap(a[i], a[right-1]);
return i;
/ the secondary routine which will
/ do the actual sorting
tatic void iqsort(int left, int right)
while (right - left > cutoff)
{
int i = partition(left, right);
if (i - left > right - i)
{
iqsort(i+1, right);
right = i - 1;
}
else
{
iqsort(left, i-1);
left = i + 1;
}
}
oid qsort2(void *array, unsigned nel,
unsigned, int (*)(const void*,const void*))
a = (int*)array; // set global pointer
iqsort(0, nel-1);
inssort(0, nel-1);